import axios from 'axios'
import * as storage from '../utils/storage'
import * as constants from '../utils/constants'
import { addRequest, refreshTokenMethod } from '@/utils/refresh'
import JSONBIG from 'json-bigint'
import { Message, Notification } from 'element-ui'
import router from '@/router'

const instance = axios.create({
  timeout: 6000,
  timeoutErrorMessage: 'timeout'
})
//处理long类型精度损失的问题
instance.defaults.transformResponse = [
  function (data) {
    const json = JSONBIG({
      storeAsString: true
    })
    const res = json.parse(data)
    return res
  }
]
instance.interceptors.request.use(config => {
  //获取短token，携带到请求头，服务端校验
  config.headers[constants.AUTH] = storage.getAccessToken(constants.ACCESS_TOKEN)
  return config
}, err => {
  return Promise.reject(err)
})
let response = {
  config: null,
  data: null
}
instance.interceptors.response.use( res => {
  // 获取到配置和后端响应的数据
  let {
    config,
    data
  } = res
  response.config = res.config
  response.data=res.data
    //短token失效
    if (data.code === 401) {
      //移除无效的短token
      storage.removeAccessToken(constants.ACCESS_TOKEN)
      //将过期请求存储起来，用来请求到新的token，再次请求
      //携带长token去请求新的短token
      return refreshTokenMethod(res)
    }else if (data.code===4007){
      //账号被禁用
      storage.removeAccessToken(constants.ACCESS_TOKEN)
      storage.removeRefreshToken(constants.REFRESH_TOKEN)
      localStorage.removeItem("expert-userInfo")
      localStorage.removeItem("profile-account")
      Message.error('账号已被禁用！')
      router.push("/login")
    } else {
     return Promise.resolve(data)
    }
}, err => {
  if (err.message === 'timeout') {
    Notification({
      title: '请求超时',
      message: '网络不佳，请求超时！',
      type: 'error'
    })
    response.data = {
        code: 408,
        msg: '请求超时',
        data: ''
      }
      return Promise.resolve(response.data)
  }

  // Message({
  //   type:'error',
  //   message: ''+err
  // })
  return Promise.reject(err)
})
export default instance
